package Formularios;

import BD.Caixa;
import BD.Caixa_Iten;
import BD.Usuarios;
import BD.clientes;
import BD.pedidos;
import BD.pedidos_Itens;
import BD.utilsPim;
import BD.Validacao;
import BD.produtos;

import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author CORE
 */
public class FormCaixa extends javax.swing.JFrame {
    Validacao vldc               = new Validacao();
    Caixa caixa                  = new Caixa();
    Caixa_Iten cxi               = new Caixa_Iten();
    pedidos ped                  = new pedidos();
    ArrayList<pedidos> lstpd     = new ArrayList<pedidos>(); 
    ArrayList<Caixa> lstcx       = new ArrayList<Caixa>();       
    ArrayList<Caixa_Iten> lstcxi = new ArrayList<Caixa_Iten>();       
    utilsPim utl                 = new utilsPim();
    Usuarios use ;   
    public int relnpedido;
    public pedidos relped;   
    public String reldesconto; 
    
    boolean aberto = true;

    /**
     * Creates new form FormCaixa
     */
    public FormCaixa() {        
        initComponents();        
        carregaCobobox();
        jtDesconto.setEditable(false);
//        setLocationRelativeTo(null);
        pnlpedido.setSelectedIndex(0);
        jpPgto.setVisible(true);        
        lstcx = caixa.getItens();        
        jDateChooser1.setVisible(false);
        jtData.setEditable(false);
        if(lstcx.size()> (0) && lstcx.get(0).getAberto())
        {   
            aberto = true;
            modovizual(true);
            atualizaTabela();
            jtSaldoInicial.setText(Float.toString(lstcx.get(0).getSaldo_inicial()));
            jtdtAbertura.setDate(lstcx.get(0).getDtabertura());
            jtData.setText(utl.getDateHoraChooser(jtdtAbertura));
            jtSaldoInicial.setEditable(false);
        
        }
        else
        {
            aberto = false;    
            modovizual(false);
            JOptionPane.showMessageDialog(rootPane, "Informe o saldo inicial do caixa");
        }    
    }
    
    
    private boolean Validacao() {
        return (vldc.Valida(jtSaldoInicial.getText(), " O Saldo inicial do Caixa !"));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jDateChooser1 = new com.toedter.calendar.JDateChooser();
        jbtnAbriFecha = new javax.swing.JButton();
        jtSaldoInicial = new javax.swing.JTextField();
        jlblPesq3 = new javax.swing.JLabel();
        jlblPesq4 = new javax.swing.JLabel();
        jpnlGeral = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jtNumeroMesaPesq = new javax.swing.JTextField();
        jlblPesq = new javax.swing.JLabel();
        jlblPesq1 = new javax.swing.JLabel();
        jbtnPesquisa = new javax.swing.JButton();
        jcbxclientePesq = new javax.swing.JComboBox();
        pnlpedido = new javax.swing.JTabbedPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtAberto = new javax.swing.JTable();
        jScrollPane4 = new javax.swing.JScrollPane();
        jtFechado = new javax.swing.JTable();
        jpPgto = new javax.swing.JPanel();
        jlblPesq2 = new javax.swing.JLabel();
        jcbxpgto = new javax.swing.JComboBox();
        jtDesconto = new javax.swing.JTextField();
        jlblPesq5 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jbtnReceber = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jtdtAbertura = new com.toedter.calendar.JDateChooser();
        jtData = new javax.swing.JTextField();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Master Pizza - Caixa");
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jbtnAbriFecha.setText("Fechar Caixa");
        jbtnAbriFecha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAbriFechaActionPerformed(evt);
            }
        });
        getContentPane().add(jbtnAbriFecha, new org.netbeans.lib.awtextra.AbsoluteConstraints(417, 11, 107, -1));

        jtSaldoInicial.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtSaldoInicialActionPerformed(evt);
            }
        });
        jtSaldoInicial.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtSaldoInicialKeyTyped(evt);
            }
        });
        getContentPane().add(jtSaldoInicial, new org.netbeans.lib.awtextra.AbsoluteConstraints(69, 11, 80, -1));

        jlblPesq3.setText("Abertura");
        getContentPane().add(jlblPesq3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 14, -1, -1));

        jlblPesq4.setText("Data Abertura");
        getContentPane().add(jlblPesq4, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 10, -1, 20));

        jpnlGeral.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jlblPesq.setText("Nº Mesa");

        jlblPesq1.setText("Cliente");

        jbtnPesquisa.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/Pesquisa.png"))); // NOI18N
        jbtnPesquisa.setText("Localizar");
        jbtnPesquisa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnPesquisaActionPerformed(evt);
            }
        });

        jcbxclientePesq.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jcbxclientePesq.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcbxclientePesqActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jlblPesq)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jtNumeroMesaPesq, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(3, 3, 3)
                .addComponent(jlblPesq1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jcbxclientePesq, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnPesquisa, javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)
                .addGap(8, 8, 8))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlblPesq)
                    .addComponent(jtNumeroMesaPesq, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jlblPesq1)
                    .addComponent(jbtnPesquisa)
                    .addComponent(jcbxclientePesq, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jpnlGeral.add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, 514, -1));

        pnlpedido.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                pnlpedidoStateChanged(evt);
            }
        });

        jtAberto.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "PD", "Mesa / Cliente", "Valor"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Object.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, true, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(jtAberto);
        if (jtAberto.getColumnModel().getColumnCount() > 0) {
            jtAberto.getColumnModel().getColumn(0).setMaxWidth(35);
            jtAberto.getColumnModel().getColumn(1).setMaxWidth(35);
            jtAberto.getColumnModel().getColumn(2).setMaxWidth(500);
            jtAberto.getColumnModel().getColumn(3).setMaxWidth(150);
        }

        pnlpedido.addTab("                   Pedidos em Aberto                     ", jScrollPane2);

        jtFechado.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "PD", "Mesa / Cliente", "Forma PGTO", "Valor"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Object.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, true, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jtFechado.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtFechadoMouseClicked(evt);
            }
        });
        jtFechado.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtFechadoKeyTyped(evt);
            }
        });
        jScrollPane4.setViewportView(jtFechado);
        if (jtFechado.getColumnModel().getColumnCount() > 0) {
            jtFechado.getColumnModel().getColumn(0).setMaxWidth(35);
            jtFechado.getColumnModel().getColumn(1).setMaxWidth(35);
            jtFechado.getColumnModel().getColumn(2).setMaxWidth(500);
            jtFechado.getColumnModel().getColumn(3).setMaxWidth(200);
            jtFechado.getColumnModel().getColumn(3).setHeaderValue("Forma PGTO");
            jtFechado.getColumnModel().getColumn(4).setMaxWidth(150);
        }

        pnlpedido.addTab("                   Pedidos Fechados                     ", jScrollPane4);

        pnlpedido.setSelectedIndex(1);

        jpnlGeral.add(pnlpedido, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 90, 514, 230));

        jlblPesq2.setText("Formas Pagamento");

        jcbxpgto.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "A VISTA", "A PRAZO 15 DIAS", "A PRAZO 30 DIAS", "A PRAZO 60 DIAS", "CARTÃO DE CREDITO", "CARTÃO DE DÉBITO" }));
        jcbxpgto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcbxpgtoActionPerformed(evt);
            }
        });

        jtDesconto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtDescontoActionPerformed(evt);
            }
        });
        jtDesconto.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jtDescontoFocusLost(evt);
            }
        });
        jtDesconto.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtDescontoKeyTyped(evt);
            }
        });

        jlblPesq5.setText("Desconto");

        jButton1.setText("...");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jpPgtoLayout = new javax.swing.GroupLayout(jpPgto);
        jpPgto.setLayout(jpPgtoLayout);
        jpPgtoLayout.setHorizontalGroup(
            jpPgtoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpPgtoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpPgtoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jcbxpgto, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jlblPesq2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpPgtoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpPgtoLayout.createSequentialGroup()
                        .addComponent(jtDesconto, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jlblPesq5))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jpPgtoLayout.setVerticalGroup(
            jpPgtoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpPgtoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpPgtoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlblPesq2)
                    .addComponent(jlblPesq5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpPgtoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jcbxpgto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtDesconto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jpnlGeral.add(jpPgto, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 330, 360, 60));

        jbtnReceber.setText("Receber pedido");
        jbtnReceber.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnReceberActionPerformed(evt);
            }
        });
        jpnlGeral.add(jbtnReceber, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 360, -1, -1));

        jButton2.setText("Atualizar Pedidos");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jpnlGeral.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 60, -1, -1));

        getContentPane().add(jpnlGeral, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, -1, 430));

        jtdtAbertura.setDateFormatString("dd/MM/yyyy HH:mm");
        getContentPane().add(jtdtAbertura, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 11, 0, -1));
        getContentPane().add(jtData, new org.netbeans.lib.awtextra.AbsoluteConstraints(274, 11, 110, -1));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void modovizual(boolean v){
        jpnlGeral.setVisible(v);
        //jtdtAbertura.setVisible(v);
        if(v)
            jbtnAbriFecha.setText("Fechar caixa");        
        else
            jbtnAbriFecha.setText("Abrir caixa");                    
        
    }
    
    private void jbtnPesquisaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnPesquisaActionPerformed
        //DefaultTableModel modeloTblab = (DefaultTableModel)jtAberto.getModel();        
        javax.swing.JTable tbl = new javax.swing.JTable();

        if(pnlpedido.getSelectedIndex() == 0)
            tbl = jtAberto;       
        else
            tbl = jtFechado;       

        if(! jtNumeroMesaPesq.getText().equals(""))
        {
            for (int i = 0; i < tbl.getRowCount(); i++) {         
                if(tbl.getValueAt(i,2).toString().equals(jtNumeroMesaPesq.getText().toString())){
                    tbl.setRowSelectionInterval(i,i);
                }    
            }
        }        
        if(jcbxclientePesq.getSelectedIndex() > (-1))    
        {
            for (int i = 0; i < tbl.getRowCount(); i++) {
                String s = jcbxclientePesq.getSelectedItem().toString();
                if(tbl.getValueAt(i,2).toString().equals(s)){
                    tbl.setRowSelectionInterval(i,i);
                }    
            }           
        }
        // reinicia os campos
        jcbxclientePesq.setSelectedIndex(-1);        
        jtNumeroMesaPesq.setText("");        
        
        /*clientes cli = new clientes();
        cli.setNome(jtPesq.getText());
        listClientes = cli.getItens();         // TODO add your handling code here:
        TravaBtns(false, true, true);
        jbtnFirstActionPerformed(evt);*/
    }//GEN-LAST:event_jbtnPesquisaActionPerformed

    private void jbtnReceberActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnReceberActionPerformed
        // TODO add your handling code here:
        //if(jpnlGeral.se)
            if (jtAberto.getSelectedRow() == (-1)){
                JOptionPane.showMessageDialog(rootPane, "Selecione um pedido");
                return;
            }
            if(pnlpedido.getSelectedIndex() == 0){
    //            while(jtAberto.getSelectedRow() > (-1)){
                cxi = new Caixa_Iten();            
                cxi.setId_pedido(jtAberto.getValueAt(jtAberto.getSelectedRow(),1).hashCode());
                cxi.setTipopgto(jcbxpgto.getSelectedItem().toString());           

                for (int i = 0; i < lstpd.size(); i++) {
                    if(lstpd.get(i).getId_pedidos() == jtAberto.getValueAt(jtAberto.getSelectedRow(),1).hashCode()){
                        if(!jtDesconto.getText().equals(""))       
                            cxi.setValor(lstpd.get(i).getValor()-Float.parseFloat(jtDesconto.getText().replace(",",".")));                            
                       else
                            cxi.setValor(lstpd.get(i).getValor());
                        break;                    
                    }                
                }
                if(cxi.incluir()){
                    ped = new pedidos();
                    ped.setId_pedidos(jtAberto.getValueAt(jtAberto.getSelectedRow(),1).hashCode());
                    relnpedido = ped.getItens().get(0).getId_pedidos();
                    //relped = ped.getItens().get(0);                            
                    //npedido = jtAberto.getValueAt(jtAberto.getSelectedRow(),1).hashCode();
                    ped.pesqfinalizado = true;
                    ped.setFinalizado(false);                
                    ped.finalizarpedido();                    
                    
                    
                    atualizaTabela();
                    //System.out.println("sss");    
                    reldesconto = jtDesconto.getText();                    
                    FormComprovante fc = new FormComprovante(this,true,this );
                    fc.ped = ped.getId_pedidos();
                    //String []args = null;
                    fc.setVisible(true);                  
                    
                    //fc.main(args);
                    //JOptionPane.showMessageDialog(rootPane, "Pedido Recebido");                    
                    jtDesconto.setText("");
                }    
                else
                    JOptionPane.showMessageDialog(rootPane, "Erro de exlusão do item");
    //            }   
            }else{//cancelar pedido                
                if(jtFechado.getSelectedRow()<0) return;
                if(!this.use.isGerente()){
                    JOptionPane.showMessageDialog(null,"Somente o gerente pode cancelar o pedido. Verifique!");
                    return;
                }
                if(JOptionPane.showConfirmDialog(rootPane, "Deseja cancelar o pedido?")==0){
                    pedidos pede = new pedidos();
                    ped = new pedidos();
                    ped.pesqfinalizado = false;
                    ped.setSiuacao("");
                    ped.setId_pedidos(jtFechado.getValueAt(jtFechado.getSelectedRow(), 1).hashCode());                
                    pede = ped.getItens().get(0);

                    Caixa_Iten cxi = new Caixa_Iten();
                    cxi.setId_caixa_iten(jtFechado.getValueAt(jtFechado.getSelectedRow(), 0).hashCode());                
                    //System.out.println(cx'i.getId_caixa());

                    if(pede.CANCELARPEDIDO()&&cxi.excluir()){
                        atualizaTabela();
                        JOptionPane.showMessageDialog(rootPane, "Pedido cancelado com sucesso");
                    }

                }
                
            }
    }//GEN-LAST:event_jbtnReceberActionPerformed

    private void jbtnAbriFechaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAbriFechaActionPerformed
        // TODO add your handling code here:
        if(!aberto){
            aberto = true;
            modovizual(true);            
            if(!jtSaldoInicial.getText().equals("0") &&!jtSaldoInicial.getText().equals("0,0")&&!jtSaldoInicial.getText().equals(""))
               caixa.setSaldo_incial(Float.parseFloat(jtSaldoInicial.getText()));
            if(caixa.AbrirCaixa())
            {    
                lstcx = new ArrayList<Caixa>();
                caixa = new Caixa();
                lstcx = caixa.getItens();
                
                caixa = lstcx.get(0);
                jtdtAbertura.setDate(caixa.getDtabertura());
                atualizaTabela();
                JOptionPane.showMessageDialog(rootPane,"Caixa aberto com sucesso");                
            }                
        }    
        else
        {
            caixa.FecharCaixa();
            relatoriofechamento();
            dispose();
        }
        
        jtSaldoInicial.setEditable(false);
            
    }//GEN-LAST:event_jbtnAbriFechaActionPerformed

    private void jcbxclientePesqActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbxclientePesqActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jcbxclientePesqActionPerformed

    private void jtSaldoInicialKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtSaldoInicialKeyTyped
        String caracteres = "0987654321.";
        if (!caracteres.contains(evt.getKeyChar() + "")) {
            evt.consume();
        }
    }//GEN-LAST:event_jtSaldoInicialKeyTyped

    private void jtSaldoInicialActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtSaldoInicialActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jtSaldoInicialActionPerformed

    private void pnlpedidoStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_pnlpedidoStateChanged
     jpPgto.setVisible(pnlpedido.getSelectedIndex() == 0);
     if(pnlpedido.getSelectedIndex() == 0)
         jbtnReceber.setText("Receber pedido");
     else
         jbtnReceber.setText("Cancelar pedido");
         
    }//GEN-LAST:event_pnlpedidoStateChanged

    private void jtFechadoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtFechadoKeyTyped
        // TODO add your handling code here:
    }//GEN-LAST:event_jtFechadoKeyTyped

    private void jtFechadoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtFechadoMouseClicked
        
        if(evt.getClickCount() == 2){
            jbtnReceberActionPerformed(null);
        }
            

        // TODO add your handling code here:
    }//GEN-LAST:event_jtFechadoMouseClicked

    private void jcbxpgtoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbxpgtoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jcbxpgtoActionPerformed

    private void jtDescontoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtDescontoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jtDescontoActionPerformed

    private void jtDescontoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtDescontoKeyTyped
        String caracteres = "0987654321.";
        if (!caracteres.contains(evt.getKeyChar() + "")) {
            evt.consume();
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_jtDescontoKeyTyped

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        FormSetGerente  fg = new FormSetGerente(this, true);
        fg.setVisible(true);
        jtDesconto.setEditable(true);
        jtDesconto.requestFocus();         
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jtDescontoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtDescontoFocusLost
        if(! jtDesconto.getText().equals("")){
            
            float d = Float.parseFloat( jtDesconto.getText().replace(",","."));
            jtDesconto.setText(utl.formatavalor(d));
        }
        jtDesconto.setEditable(false);
    }//GEN-LAST:event_jtDescontoFocusLost

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        atualizaTabela();
        carregaCobobox();
    }//GEN-LAST:event_jButton2ActionPerformed
    private void relatoriofechamento(){
        String []args = null;
        //aki vfai vir o fechamento do caixa 
        FormRelatorioCaixa fcxr = new FormRelatorioCaixa(this, true);
        fcxr.main(args);
        
    }
    private void carregaCobobox(){        
        jcbxclientePesq.removeAllItems();
        pedidos pl = new pedidos();
        pl.setSiuacao("A");
        pl.setFinalizado(false);
        pl.pesqfinalizado = true;
        
        clientes cli = new clientes();
        ArrayList<pedidos>  listCli = new ArrayList<pedidos>();
        listCli = pl.getItens();
        
        for (int i = 0; i < listCli.size(); i++) {
            if(listCli.get(i).getId_clientes()>0)
                jcbxclientePesq.addItem(listCli.get(i).getCliente_nome());
        }
        jcbxclientePesq.setSelectedIndex(-1);                
    }
    
    
    private void atualizaTabela(){
        cxi = new Caixa_Iten();
        ped = new pedidos();
        cxi.setId_caixa(caixa.getId_caixa());
        lstcxi = cxi.getItens();
        lstpd = ped.getItens();

        DefaultTableModel modeloTblab = (DefaultTableModel)jtAberto.getModel();        
        DefaultTableModel modeloTblfc = (DefaultTableModel)jtFechado.getModel();        
        while(jtAberto.getRowCount()>0 ){
            modeloTblab.removeRow(0);
        }
        while(jtFechado.getRowCount()>0 ){
            modeloTblfc.removeRow(0);
        }
        
        int lina = 0,linf = 0;

        float valorTt = 0;
        for(int i = 0; i < lstpd.size();i++){
            modeloTblab.addRow(new String[ modeloTblab.getColumnCount() ]);//adciona linha            
            jtAberto.setValueAt(lstpd.get(i).getId_pedidos(), lina, 1);
            if(lstpd.get(i).getMesa() > 0 )
                jtAberto.setValueAt(lstpd.get(i).getMesa(), lina, 2);
            else
                jtAberto.setValueAt(lstpd.get(i).getCliente_nome(), lina, 2);                   
            jtAberto.setValueAt(utl.formatavalor(lstpd.get(i).getValor()), lina,3);
            lina = lina +1;                                    

        }

        for(int i = 0; i < lstcxi.size();i++){            
            modeloTblfc.addRow(new String[ modeloTblfc.getColumnCount() ]);//adciona linha            
            jtFechado.setValueAt(lstcxi.get(i).getId_caixa_iten(), linf, 0);            
            jtFechado.setValueAt(lstcxi.get(i).getId_pedido(), linf, 1);            
            jtFechado.setValueAt(lstcxi.get(i).cliente_mesa, linf, 2);// aki vem o cliente ou a mesa              
            jtFechado.setValueAt(lstcxi.get(i).getTipopgto(), linf,3);
            jtFechado.setValueAt(utl.formatavalor(lstcxi.get(i).getValor()), linf,4);
            linf = linf +1;                               
        }
            
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FormCaixa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FormCaixa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FormCaixa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FormCaixa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FormCaixa().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private com.toedter.calendar.JDateChooser jDateChooser1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton jbtnAbriFecha;
    private javax.swing.JButton jbtnPesquisa;
    private javax.swing.JButton jbtnReceber;
    private javax.swing.JComboBox jcbxclientePesq;
    private javax.swing.JComboBox jcbxpgto;
    private javax.swing.JLabel jlblPesq;
    private javax.swing.JLabel jlblPesq1;
    private javax.swing.JLabel jlblPesq2;
    private javax.swing.JLabel jlblPesq3;
    private javax.swing.JLabel jlblPesq4;
    private javax.swing.JLabel jlblPesq5;
    private javax.swing.JPanel jpPgto;
    private javax.swing.JPanel jpnlGeral;
    private javax.swing.JTable jtAberto;
    private javax.swing.JTextField jtData;
    private javax.swing.JTextField jtDesconto;
    private javax.swing.JTable jtFechado;
    private javax.swing.JTextField jtNumeroMesaPesq;
    private javax.swing.JTextField jtSaldoInicial;
    private com.toedter.calendar.JDateChooser jtdtAbertura;
    private javax.swing.JTabbedPane pnlpedido;
    // End of variables declaration//GEN-END:variables
}
